<template>
  <div class="bw-slot-js-extnd-content">
    <div class="js-content" ref="codeEdit"></div>
  </div>
</template>

<script lang="ts" setup>
import * as monaco from 'monaco-editor'
import BwMonacoEditor from '@/utils/monacoEditor'

import { ref, unref, toRaw } from 'vue'
interface BwSlotJSExtndProps {
  value?: string
}

const bwMonacoEditor = new BwMonacoEditor()
const emit = defineEmits(['update:value'])
const props = withDefaults(defineProps<BwSlotJSExtndProps>(), {})

const codeEdit = ref()
const curValue = ref<string>('')
const curEditor = ref<monaco.editor.IStandaloneCodeEditor | undefined>()

const initMonacoEditor = (value?: string) => {
  curValue.value = value || 'export default {\n  extnd (params) {\n  }\n}'
  curEditor.value = bwMonacoEditor.create({
    menus: undefined,
    snippets: undefined,
    domElement: unref(codeEdit),
    options: {
      value: unref(curValue),
      wordWrap: 'on',
      language: 'typescript',
    },
  })

  /** 监听编辑器内容变化 */
  const curEdit = unref(curEditor)
  if (curEdit) {
    curEdit.onDidChangeCursorPosition(function (e) {
      if (curEdit) {
        let readOnly = false
        if (e.position.lineNumber <= 2) {
          readOnly = true
        }
        toRaw(curEdit).updateOptions({
          readOnly: readOnly,
        })
      }
    })

    curEdit.onDidChangeModelContent(() => {
      try {
        const curText = toRaw(curEdit).getValue()
        curValue.value = curText
        emit('update:value', curText)

        console.log('update:value', curText)
      } catch (error) {
        console.warn('编辑器报错')
      }
    })
  }
}

defineExpose({
  init() {
    initMonacoEditor(props.value)
  },
})
</script>

<style lang="less" scoped>
.bw-slot-js-extnd-content {
  width: 100%;
  height: auto;
  min-height: 200px;
  max-height: 500px;
  border-radius: 3px;
  border: 1px solid #e8e8e8;

  .js-content {
    width: 100%;
    height: 100%;
    min-height: 200px;
  }
}
</style>
